package com.example.dell.intelligentagriculture.utils;


import android.content.SharedPreferences;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 连接沙盘
 */
public class HttpUtil {
    SharedPreferences sp;

    public HttpUtil() {
    }

    public HttpUtil(SharedPreferences sp) {
        this.sp = sp;
    }

    /***
     * http://  192.168.1.119   :8890 /type/jason/action/     getSensor
     * http://  192.168.1.119   :8890/type/jason/action/     getConfig
     * http://  192.168.1.119   :8890/type/jason/action/     setConfig
     * http://  192.168.1.119   :8890/type/jason/action/     control
     * http://  192.168.1.119   :8890/type/jason/action/     getContorllerStatus
     *
     */
    private final String HEAD = "http://";
    private final String BASE_URL = ":8890/type/jason/action/";
    Gson gson;
    String ip;

    /**
     * 封装url地址
     *
     * @param ip
     * @param action
     * @return
     */
    public String getUrl(String ip, String action) {
        String url = HEAD + ip + BASE_URL + action;
        return url;
    }

    /***
     *
     * @param value 用户名对应的value
     * @param myApp 获取用户输入并封装的ip
     * @param action url的最终地址
     * @return 服务器响应的数据
     * @throws IOException
     */
    public String connectServer(String value, MyApp myApp, String action) throws IOException {
        gson = new Gson();
        ip = myApp.getIp();
        String url = getUrl(ip, action);
        //做网络连接用
        OkHttpClient client = new OkHttpClient();
        //获取请求体 请求的key—value
        RequestBody body = new FormBody.Builder().add("username", value).build();
        //向服务器发送请求
        Request.Builder builder = new Request.Builder();
        //设置连接方式（post / get）
        builder.post(body);
        builder.url(url);
        Request request = builder.build();//获取请求对象
        //发送请求  创建连接
        Call call = client.newCall(request);
        //执行网络连接（联网） ,获取到服务器返回的响应 ,联网的操作，必须执行在子线程
        Response response = call.execute();
        //取出响应中的数据
        String data = response.body().string();
        return data;
    }

    /**
     * 获取传感器的值
     */
    public Agriculture getSensor(MyApp myApp) throws IOException {
        String data = connectServer("admin", myApp, "getSensor");
        Agriculture agriculture = new Agriculture();
        agriculture = gson.fromJson(data, Agriculture.class);
        return agriculture;
    }

    /**
     * 获取传感器的告警值范围(最大值和最小值) 保存到文件中
     */
    public void getConfig(MyApp myApp) throws IOException {
        String data = connectServer("", myApp, "getConfig");
        // 获取编辑器
        SharedPreferences.Editor edit = sp.edit();
        //使用编辑器向文件中写入数据
        edit.putString("extreme", data);
        //提交
        edit.commit();
    }

    /**
     * 控制器协议  (操控沙盘)
     */
    public void control(MyApp myApp, String controlNmae, int controlValue) throws JSONException, IOException {
        //获取url
        String url = getUrl(myApp.getIp(), "control");
        //获取连接
        OkHttpClient client = new OkHttpClient();
        //获取json对象
        JSONObject myJson = new JSONObject();
        //向json存放数据  {'Buzzer':1}
        myJson.put(controlNmae, controlValue);
        //设置请求体  参数1：数据传输协议
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), String.valueOf(myJson));
        //设置请求对象
        Request request = new Request.Builder().post(body).url(url).build();
        client.newCall(request).execute();
    }

    /**
     * 获取控制器状态的协议
     */
    public int[] getContorllerStatus(MyApp myApp) throws IOException, JSONException {
        String data = connectServer("", myApp, "getContorllerStatus");
        JSONObject json = new JSONObject(data);
        int waterPump = json.getInt("WaterPump");//水
        int blower = json.getInt("Blower");//风扇
        int roadlamp = json.getInt("Roadlamp");//灯
        int buzzer = json.getInt("Buzzer");//报警

        int[] dataArr = {waterPump, blower, roadlamp, buzzer};
        return dataArr;
    }
}
